package cn.szq.concurrent.thread.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

/**
 * @ClassName: RunDemo1
 * @Description:
 * @Author: szq
 * @Date: 2021-10-25 08:26:25
 */
public class RunDemo1 {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch cwd = new CountDownLatch(5);
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        IntStream.rangeClosed(1, 5).forEach(t->{
            final int num = t;
            Runnable runnable = () -> {
                try {
                    Thread.sleep((long) (Math.random() * 10000));
                    System.out.println(num + "号运动员完成了比赛。");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    cwd.countDown();
                }
            };
            executorService.submit(runnable);
        });
        System.out.println("等待五个运动员都跑完。。。");
        cwd.await();
        System.out.println("所有人都跑完了，比赛结束。");
    }
}
